(function(){
	var pagenum=10;//每页数量
	var curpage=1;//当前页面
	var totalPage=0;//总页数
	//获取列表
	function getlist(curpage,pagenum){
	   var mallName=$("#mallName").val();
	   var priceType=$("#priceType").val()=="全部"?"":$("#priceType").val();
	   var mallStatus=$("#mallStatus").val()=="全部"?"":$("#mallStatus").val();
	   var startDate=$("#datepicker").val();
	   var endDate=$("#datepicker2").val();
	   $.ajax({
			url:'http://web.icecn.net/web/findGoodsList.json',
			type:'POST',
			async:true,
			data:{
                offset:pagenum*(curpage-1),
				limit:pagenum,
				mallName:mallName,
				priceType:priceType,
				mallStatus:mallStatus,
				startDate:startDate,
				endDate:endDate
			},
			xhrFields:{withCredentials:true},
			dataType: "json",
			success: function(data){
				if(data.code == 200 ){
				    dataset=data.t.result;
					if(dataset && dataset.length > 0){
					   var html = template('datalist',{dataset:dataset});
					   $("#example1").html(html);
					   totalPage=data.t.totalPage;
					   $(".pageinfo").html("当前"+curpage+"页/共"+totalPage+"页");
					   $(".curpage").val(curpage);
					   if(curpage==1){$(".prev").addClass("disabled")}else{$(".prev").removeClass("disabled")}
					   if(curpage==totalPage){$(".next").addClass("disabled")}else{$(".next").removeClass("disabled")}
					}else{
					  $("#example1").html("<tbody><tr><td>查不到数据</td></tr></tbody>");
					};
				}
			}
	   });
	}
	var Page = {
		init:function(){
			this.render();
			this.event();
		},
		//绑定事件
		event:function(){
			//上一页
		    $(".prev").click(
			    function(){
					if(curpage>1){
				     	curpage=curpage-1;
					    getlist(curpage,pagenum);
					}
			    }
			)
			//下一页
		    $(".next").click(
			    function(){
					if(curpage<totalPage){
				     	curpage=curpage+1;
					    getlist(curpage,pagenum);
					}
			    }
			)
			//页码跳转
			$(".gopage").click(
			    function(){
					if($(".curpage").val()>=1&&$(".curpage").val()<=totalPage){
				    	curpage=parseInt($(".curpage").val());
					    getlist(curpage,pagenum)
					}else{
						$(".curpage").val(curpage);
					}
			    }
			)
			//搜索按钮
			$(".btnsearch").click(function(){
				curpage=1
			  	getlist(curpage,pagenum)
			})
			//全选
			$(".content").on("click", '.allcheck', function() {
				if ($(".allcheck").attr("checked")) { 
				    $(".allcheck").attr("checked", false)
					$("input[name=items]").each(function() {  
						$(this).attr("checked", false);  
					});  
				} else {  
				    $(".allcheck").attr("checked", true)
					$("input[name=items]").each(function() {  
						$(this).attr("checked", true);  
					});  
				}  
			})
			//删除按钮
			$(".content-wrapper").on("click", '.delete', function() {
				if($(this).attr("data-id")>0){
				   $("#modal-delete .modal-body").attr("data-id",$(this).attr("data-id"))
				   $("#modal-delete .modal-body").html("确认删除该数据吗？")
				}else{
				   $("#modal-delete .modal-body").removeAttr("data-id");
				   $("#modal-delete .modal-body").html("确认批量删除数据吗？")
				}
			})
			//确认删除
			$(".btndelete").click(function(){
			   var id=$("#modal-delete .modal-body").attr("data-id");
			   if(id>0){
				    id=$("#modal-delete .modal-body").attr("data-id");
			   }else{
				    id="";
					$("input[name=items]").each(function() {
						if ($(this).prop("checked")) {
							id += ","+$(this).val();
						}
					}); 
					id=id.substr(1)
			   }
			   if(id==""){
			     alert("请选择数据");
				 return;
			   }
			   $.ajax({
					url:'http://web.icecn.net/web/deleteGoods.json',
					type:'POST',
					async:true,
					data:{
						id:id
					},
					dataType: "json",
					xhrFields:{withCredentials:true},
					success: function(data){
						if(data.code === 200 ){
							$("#modal-delete").modal('hide');
							getlist(curpage,pagenum);
						}else{
						    alert("删除失败")	
						}
					}
			   });
		    })
			//批量上架下架按钮
			$(".content-wrapper").on("click", '.updateStatus', function() {
				var Status=$(this).attr("data-Status");
				$("#modal-updateStatus .modal-body").html("确认"+$(this).html()+"?")
				$("#modal-updateStatus .modal-body").attr("data-Status",Status)
				
			})
			//确认上架下架
			$(".btnupdateStatus").click(function(){
			   id="";
			   $("input[name=items]").each(function() {
					if ($(this).prop("checked")) {
						id += ","+$(this).val();
					}
			   }); 
			   id=id.substr(1)
			   if(id==""){
			     alert("请选择数据");
				 return;
			   }
			   var keyWord=$("#modal-updateStatus .modal-body").attr("data-Status")
			   $.ajax({
					url:'http://web.icecn.net/web/updateGoodsStatus.json',
					type:'POST',
					async:true,
					data:{
						id:id,
						status:keyWord
					},
					xhrFields:{withCredentials:true},
					dataType: "json",
					success: function(data){
						if(data.code === 200 ){
							$("#modal-updateStatus").modal('hide');
							getlist(curpage,pagenum);
						}else{
						    alert("操作失败")	
						}
					}
			   });
		    })
			//新建修改按钮
			$(".content-wrapper").on("click", '.addupdate', function() {
				var id=$(this).attr("data-id");
				if(id!=null){
				  $("#modal-addupdate .modal-title").html("修改商品");
				  $("#id").val(id);
				  $.ajax({
						url:'http://web.icecn.net/web/findGoodsListForB.json',
						type:'POST',
						async:true,
						data:{
							id:id
						},
						xhrFields:{withCredentials:true},
						dataType: "json",
						success: function(data){
							if(data.code == 200 ){
							  var d= data.t;
							  $("#mall_name").val(d.mallName);
							  $("#mall_type").val(d.mallType);
							  $("#price_type").val(d.author);
							  $("#mall_price").val(d.mallPrice);
							  $("#stock_num").val(d.stockNum);
							  $("#limited_num").val(d.limitedNum);
							  $("#orderby_num").val(d.orderbyNum);
							  $("#mall_status").val(d.mallStatus=="上架"?"是":"否");
							  $("#price_type").val(d.priceType);
				              CKEDITOR.instances.editor1.setData(d.mallRemarks);
							  $("#photoCover1").val("");
							  $(".imgfilelist").html("");
							  for(var i=0;i<d.goodsPic.length;i++){
								 $(".imgfilelist").append("<img src='"+d.goodsPic[i].picUrl+"' class='deleteimg'/>")	
							  }
							}
						}
				  });
				}else{
				  $("#modal-addupdate .modal-title").html("新建商品")
				  $("#id").val("");
				  $("#mall_name").val("");
				  $("#mall_type option:first").prop("selected", 'selected');
				  $("#price_type option:first").prop("selected", 'selected');
				  $("#mall_price").val("");
				  $("#stock_num").val("");
				  $("#limited_num").val("");
				  $("#orderby_num").val("");
				  $("#mall_status option:first").prop("selected", 'selected');
				  $("#photoCover1").val("");
				  $("#lefilelist").val("");
				  $(".imgfilelist").html("");
				  CKEDITOR.instances.editor1.setData("")
				}
			})
			//确认修改按钮
			$(".btnaddupdate").click(function(){
				 var id=$("#id").val();
				 var mall_name=$("#mall_name").val();
				 var mall_type=$("#mall_type option:selected").val();
				 var price_type=$("#price_type option:selected").val();
				 var mall_price=$("#mall_price").val();
				 var stock_num=$("#stock_num").val();
				 var limited_num=$("#limited_num").val();
				 var orderby_num=$("#orderby_num").val()==""?0:$("#orderby_num").val();
				 var mall_status=$("#mall_status option:selected").val()=="是"?"上架":"下架";
				 var content=CKEDITOR.instances.editor1.getData().replace(/<[^>].*?>/g,"").replace(/\ /g,"");;
				 var goodPic="";
				 var img=$(".deleteimg");
				 if(img.length>0){
				   for(var i=0;i<img.length;i++){
					  var a="{'picUrl':'"+img[i].src+"'},"
					  goodPic+=a
				   }	 
				 }
				 goodPic="["+goodPic+"]";
				 if(mall_name==""){alert("请输入商品名称"); return}
				 if(mall_price==""){alert("请输入商品价格"); return}
				 if(stock_num==""){alert("请输入库存"); return}
				 if(limited_num==""){alert("请输入限购"); return}
				 if(goodPic=="[]"){alert("请上传商品图片"); return}
				 if(id>0){
					 $.ajax({
						url:'http://web.icecn.net/web/updateGoods.json',
						type:'POST',
						async:true,
						data:{
							id:id,
							mallName:mall_name,
							mallType:mall_type,
							mallPrice:mall_price,
							priceType:price_type,
							stockNum:stock_num,
							limitedNum:limited_num,
							orderbyNum:orderby_num,
							mallStatus:mall_status,
							mallRemarks:content,
							goodPic:goodPic
						},
						xhrFields:{withCredentials:true},
						dataType: "json",
						success: function(data){
							if(data.code === 200 ){
								$("#modal-addupdate").modal('hide');
								getlist(curpage,pagenum);
							}else{
								alert("操作失败")	
							}
						}
				     });
				 }else{
					 $.ajax({
						url:'http://web.icecn.net/web/insertGoods.json',
						type:'POST',
						async:true,
						xhrFields:{withCredentials:true},
						data:{
							mallName:mall_name,
							mallType:mall_type,
							mallPrice:mall_price,
							priceType:price_type,
							stockNum:stock_num,
							limitedNum:limited_num,
							orderbyNum:orderby_num,
							mallStatus:mall_status,
							mallRemarks:content,
							goodPic:goodPic
						},
						dataType: "json",
						success: function(data){
							if(data.code === 200 ){
								$("#modal-addupdate").modal('hide');
								getlist(curpage,pagenum);
							}else{
								alert("操作失败")	
							}
						}
				     });
				 }
			})
			//图片上传
			function fileupload(input,img,photoCover){
				var fileObj = document.getElementById(input).files[0];
				$.ajax({
					url:'http://39.106.145.173:8087/leveling/getToken.json',
					type:'POST',
					async:true,
					data:{
					},
					dataType: "json",
					success: function(data){
						var form = new FormData;
						form.append("file",fileObj);
						form.append("key",new Date().getTime()+".jpg");
						form.append("token",data.t.token);
						var domian=data.t.domain;
						$.ajax({
							url:'http://up.qiniu.com',
							type: 'POST',
							data:form,
							async: false,
							cache: false,
							contentType: false,
							processData: false,
							dataType: "json",
							success: function(data) {
							   $("."+img).append("<img src='"+domian+"/"+data.key+"' class='deleteimg'/>")	
							   $("#"+photoCover).val(""+domian+"/"+data.key+"");
							},
						});	
					}
				});				
			}
			$("#lefilelist").change(
			  function(){
				 fileupload("lefilelist","imgfilelist","photoCover1")
				 $("#lefilelist").val("");;
			  }
			)
			//删除图片
			$(".content-wrapper").on("click", '.deleteimg', function() {
				if (confirm("确认删除图片吗？")==true){ 
				  $(this).remove()
				}else{ 
				  return false; 
				} 
			})
		},
		//渲染页面
		render:function(){
			getlist(curpage,pagenum)
		}
	};
	Page.init();
})();